package com.tegtech.common.domain;

import java.io.Serializable;

import com.tegtech.common.enums.HttpStatus;
import com.tegtech.common.enums.IHttpStatus;
import com.tegtech.common.exception.BaseException;
import com.tegtech.common.utils.MessageUtils;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 通用请求响应结构体
 * @Author Jun
 * @date 2020年11月18日 下午6:31:48
 */
@Data
@NoArgsConstructor
public class Result implements Serializable {
	
	private static final long serialVersionUID = 1L;

	/** 状态码 */
	private int code;

	/** 返回信息 */
	private String msg = StrUtil.EMPTY;

	/** 数据对象 */
	private Object data = StrUtil.EMPTY;
	
	public Result(int code) {
		super();
		this.code = code;
	}
	
	public Result i18n(String key, Object... args) {
		this.msg = MessageUtils.message(key, args);
		return this;
	}
	
	public Result msg(String msg) {
		this.msg = msg;
		return this;
	}
	
	public Result msg(String msg, Object ... params) {
		this.msg = StrUtil.format(msg, params);
		return this;
	}
	
	public Result data(Object data) {
		this.data = data;
		return this;
	}
	
	public static Result ok() {
		return new Result(HttpStatus.SUCCESS.getCode());
	}
	
	public static Result err(int code) {
		return new Result(code);
	}
	
	public static Result err() {
		return err(HttpStatus.ERROR.getCode());
	}
	
	public static Result err(BaseException e) {
		Integer code = e.getCode();
		if(code == null) {
			code = HttpStatus.ERROR.getCode();
		}
		return err(code).msg(e.getMessage());
	}
	
	public static Result err(Exception e) {
		return err().msg(e.getMessage());
	}
	
	public static Result err(IHttpStatus httpStatus) {
		return err(httpStatus.getCode()).i18n(httpStatus.getMessage());
	}
	
}
